package top.linuyx.exception;

import cn.hutool.core.util.StrUtil;
import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import top.linuyx.enums.ResponseEnum;
import top.linuyx.pojo.response.ResponseData;

import java.util.List;

/**
 * @Author Linuyx
 * @Description 全局业务异常处理类
 * @Date Created in 2021-04-08 15:22
 */

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 自定义业务异常
     *
     * @param ex GlobalException
     * @return 异常信息
     */
    @ExceptionHandler(GlobalException.class)
    @ResponseBody
    public ResponseData globalExceptionHandler(GlobalException ex) {
        return ResponseData.fail(ex.getCode(), ex.getMessage());
    }

    /**
     * 参数校验异常
     *
     * @param ex MethodArgumentNotValidException
     * @return 异常信息
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public ResponseData methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException ex) {
        BindingResult bindingResult = ex.getBindingResult();
        //获取所有异常
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        //拿到第一个异常
        ObjectError objectError = allErrors.get(0);
        //获取异常详细信息
        String message = objectError.getDefaultMessage();
        return ResponseData.fail(ResponseEnum.PARAM_ERROR.getCode(), message);
    }

    /**
     * 未经授权异常
     * @param ex UnauthorizedException
     * @return 异常信息
     */
    @ExceptionHandler(UnauthorizedException.class)
    @ResponseBody
    public ResponseData unauthorizedExceptionHandler(UnauthorizedException ex){
        return ResponseData.fail(ResponseEnum.AUTHORIZE_ERROR.getCode(), ResponseEnum.AUTHORIZE_ERROR.getMessage());
    }

    /**
     * 其他异常
     *
     * @param ex Exception
     * @return 异常信息
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseData exception(Exception ex) {
        return ResponseData.fail(ResponseEnum.SYSTEM_ERROR.getCode(), ResponseEnum.SYSTEM_ERROR.getMessage());
    }

}
